<template>
	<uni-popup ref="popupRef" type="bottom" @change="popupToggle">
		<view class="page">
			<view class="page_body">
				<uni-forms ref="formRef" :label-width="100" label-align="right" :model="formData" :rules="rules">
					<view class="tempalte_title">
						<uni-forms-item required label="字段名称" name="label">
							<uni-easyinput v-model="formData.label" placeholder="请输入" :cursorSpacing="20" :disabled="disabled"
								:maxlength="12" />
						</uni-forms-item>
					</view>
					<uni-forms-item required label="字段类型" name="type">
						<cl-select-picker :options="fieldTemplateList" labelFiled="typeName" valueFiled="type"
							v-model="formData.type" :disabled="disabled" @submit="handleTypeSubmit"></cl-select-picker>
					</uni-forms-item>
					<uni-forms-item v-if="formData.type === 'input'" label="默认值" name="defaultVal">
						<uni-easyinput v-model="formData.defaultVal" type="text" placeholder="请输入" :disabled="disabled"
							:cursorSpacing="20" />
					</uni-forms-item>
					<uni-forms-item v-if="formData.type === 'numberInput'" label="默认值" name="defaultVal">
						<uni-easyinput v-model="formData.defaultVal" type="digit" placeholder="请输入" :disabled="disabled"
							:cursorSpacing="20" />
					</uni-forms-item>
					<uni-forms-item name="required" label="是否必填">
						<uni-data-checkbox style="position: relative; top: 8rpx" v-model="formData.required" :disabled="disabled"
							:localdata="[
                { text: '是', value: 1 },
                { text: '否', value: 0 },
              ]" />
					</uni-forms-item>
					<uni-forms-item v-if="formData.type === 'select'" label="默认值" name="defaultVal">
						<cl-more-select-picker v-model="formData.defaultVal" :options="formData.options"
							:disabled="disabled"></cl-more-select-picker>
					</uni-forms-item>
					<uni-forms-item v-if="formData.type === 'select'" label="下拉选项" name="options" required>
						<view class="options_box" v-for="(option, index) in formData.options || []" :key="index">
							<uni-easyinput v-model="formData.options[index]" type="text" placeholder="请输入下拉选项值" :disabled="disabled"
								:cursorSpacing="20" />
							<image v-if="index === formData.options.length - 1 && !disabled" class="options_box_add"
								src="@/static/add_icon.png" @click="handleChangeOption('add')" />
							<image v-if="formData.options.length > 1 && !disabled" class="options_box_del" src="@/static/del_icon.png"
								@click="handleChangeOption('del', index)" />
						</view>
					</uni-forms-item>
					<uni-forms-item v-if="formData.type === 'date'" label="时间模式" name="mode">
						<cl-select-picker :options="dateModeList" v-model="formData.mode" @submit="formData.value.defaultVal = ''"
							:disabled="disabled"></cl-select-picker>
					</uni-forms-item>
					<uni-forms-item v-if="formData.type === 'date'" label="默认值" name="defaultVal">
						<cl-date-picker v-model="formData.defaultVal" :dateType="formData.mode"
							:disabled="disabled"></cl-date-picker>
					</uni-forms-item>
					<uni-forms-item v-if="formData.type === 'upImage'" label="最大上传个数" name="maxLength">
						<uni-easyinput type="number" v-model="formData.maxLength" :disabled="disabled" :cursorSpacing="20" />
					</uni-forms-item>
					<uni-forms-item v-if="formData.type === 'upImage'" label="图片大小上限" name="maxSize">
						<uni-easyinput type="number" v-model="formData.maxSize" :disabled="disabled" :cursorSpacing="20" />
					</uni-forms-item>
				</uni-forms>
			</view>
			<view v-if="disabled" class="page_tip">模板已有填报数据，无法编辑</view>
			<view v-else class="g_bottom_box">
				<view class="g_bottom_box_btn" @click="handleSubmit">保存</view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	import {
		cloneDeep,
		values
	} from 'lodash'
	const props = defineProps({
		disabled: {
			type: Boolean,
			default: false,
		},
	})
	const formData = ref({
		type: 'input',
		typeName: '输入框',
		placeholder: '请输入',
		defaultVal: '',
		required: 0,
	})

	const emits = defineEmits(['saveField'])

	// 字段类型模板
	const fieldTemplateList = [{
			type: 'input',
			typeName: '输入框',
			placeholder: '请输入',
			defaultVal: '',
			required: 0,
		},
		{
			type: 'numberInput',
			typeName: '数字输入框',
			placeholder: '请输入',
			defaultVal: undefined,
			required: 0,
		},
		{
			type: 'select',
			typeName: '下拉框',
			options: ['下拉选项'],
			defaultVal: [],
			required: 0,
		},
		{
			type: 'date',
			typeName: '时间选择器',
			mode: 'YYYY-MM-DD',
			defaultVal: '',
			required: 0,
		},
		{
			type: 'upImage',
			typeName: '图片上传',
			maxLength: 5,
			maxSize: 5,
			defaultVal: [],
			required: 0,
		},
	]
	// 时间模式
	const dateModeList = [
		'YYYY',
		'YYYY-MM',
		'YYYY-MM-DD',
		'YYYY-MM-DD hh',
		'YYYY-MM-DD hh:mm',
		'YYYY-MM-DD hh:mm:ss',
		'hh',
		'hh:mm',
		'hh:mm:ss',
	]

	const rules = {
		label: {
			rules: [{
				required: true,
				errorMessage: '请输入字段名称'
			}],
		},
		options: {
			rules: [{
					required: true,
					errorMessage: '请输入字段名称'
				},
				{
					validateFunction: (rule, value, data, callback) => {
						if (value.some((item) => !item)) {
							callback('选项不能包含空值！')
						} else if (new Set(value).size !== value.length) {
							callback('选项值不能重复！')
						} else {
							return true
						}
					},
				},
			],
		},
	}

	// 类型切换确认事件
	const handleTypeSubmit = (type) => {
		const label = formData.value.label
		const field_id = formData.value.field_id
		if (!type) {
			formData.value = {
				label
			}
		} else {
			let curTemplateFieldData = fieldTemplateList.find(
				(item) => item.type === type
			)
			formData.value = Object.assign(curTemplateFieldData, {
				label,
				field_id
			})
		}
	}
	// 新增下拉
	const handleChangeOption = (type, index) => {
		if (type === 'add') {
			formData.value.options.push('下拉选项')
		} else {
			formData.value.options.splice(index, 1)
		}
	}
	// 提交
	const formRef = ref()
	const handleSubmit = async () => {
		await formRef.value.validate()
		emits('saveField', JSON.parse(JSON.stringify(formData.value)))
		close()
		formData.value = {
			type: 'input',
			typeName: '输入框',
			placeholder: '请输入',
			defaultVal: '',
			required: 0,
		}
	}
	const popupRef = ref()

	// 弹窗打开
	const open = () => {
		popupRef.value.open()
	}
	// 弹窗关闭
	const close = () => {
		popupRef.value.close()
	}
	// 修改设置默认值
	const setData = (data) => {
		formData.value = data
	}

	// 关闭弹窗清空数据
	const popupToggle = ({
		show
	}) => {
		if (show === false) {
			formData.value = cloneDeep(fieldTemplateList[0])
			formRef.value.clearValidate()
		}
	}

	defineExpose({
		close,
		open,
		setData,
	})

	// 如果下拉数据发生变化就清空下拉默认值
	watch(
		() => formData.value?.options,
		(newV) => {
			if (formData.value.type === 'select') {
				formData.value.defaultVal = []
			}
		}, {
			deep: true
		}
	)
</script>

<style scoped lang="scss">
	.page {
		padding: 10rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		width: 100vw;
		overflow: hidden;
		background-color: #fff;

		&_body {
			margin-top: 20rpx;
			flex: 1;
		}

		.options_box {
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;

			&_add,
			&_del {
				margin-left: 10rpx;
				width: 40rpx;
				height: 40rpx;
				cursor: pointer;
			}
		}

		&_tip {
			margin-bottom: 20rpx;
			text-align: center;
			color: $uni-text-color-grey;
			font-size: 24rpx;
		}

		&_bottom {
			background-color: #fff;

			&_btn {
				margin: 20rpx auto;
				padding: 20rpx;
				width: 600rpx;
				text-align: center;
				color: #fff;
				background-color: $uni-color-primary;
				border-radius: 40rpx;
			}
		}
	}
</style>